package com.yuntsg.nnsfcp.service;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.query_dsl.BoolQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch._types.query_dsl.TermQuery;
import co.elastic.clients.elasticsearch.core.DeleteByQueryRequest;
import co.elastic.clients.elasticsearch.core.DeleteByQueryResponse;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;
import com.yuntsg.nnsfcp.common.beans.ResultBean;
import com.yuntsg.nnsfcp.common.exceptions.BaseResponseCode;
import com.yuntsg.nnsfcp.common.utils.CheckUtil;
import com.yuntsg.nnsfcp.common.utils.FileUtil;
import com.yuntsg.nnsfcp.common.utils.StringUtil;
import com.yuntsg.nnsfcp.common.utils.UserUtil;
import com.yuntsg.nnsfcp.entity.*;
import com.yuntsg.nnsfcp.front.entity.*;
import com.yuntsg.nnsfcp.front.mapper.*;
import com.yuntsg.nnsfcp.service.back.BackService;
import com.yuntsg.nnsfcp.service.back.Role.RolePermissionService;
import com.yuntsg.nnsfcp.service.front.Constants;
import com.yuntsg.nnsfcp.service.front.ut.DateUtil;
import com.yuntsg.nnsfcp.util.IndexConfig;
import com.yuntsg.ruiijn.controller.user.UploadLocalFileController;
import com.yuntsg.ruiijn.database.entity.*;
import com.yuntsg.ruiijn.database.mapper.TextSelfDbMapper;
import com.yuntsg.ruiijn.database.mapper.TextSelfMd5Mapper;
import com.yuntsg.ruiijn.database.mapper.WosBasicMapper;
import com.yuntsg.ruiijn.databse_search.entity.FileDetailsTxt;
import com.yuntsg.ruiijn.paperana.service.MatchService;
import com.yuntsg.ruiijn.paperana.utils.SmallTool;
import com.yuntsg.ruiijn.paperana.utils.StrUtils;
import com.yuntsg.ruiijn.service.ManualCheckService;
import common.util.PDFMERGE;
import common.util.PdfUtil;
import common.util.VerifyUtil;
import common.util.WordUtil;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.yuntsg.ruiijn.controller.client.ClientController.getPdf;
import static com.yuntsg.ruiijn.paperana.service.ArticleRepeatSummary.pdfToTxtRuijin;
import static com.yuntsg.ruiijn.service.AsyncService.localDateFilePath;


@Service
@Slf4j
//@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@SuppressWarnings("all")
public class CommonService {

    @Value("${upload.path}")
    public String uploadPath;
    @Resource

    ElasticsearchClient client;

    @Resource
    private FundMap fundMap;

    @Resource
    WosBasicMapper wosBasicMapper;

    @Resource
    ManualCheckService manualCheckService;

    @Resource
    HttpServletResponse response;
    @Resource
    TextSelfDbMapper textSelfDbMapper;

    @Resource
    TPermissionMapper tPermissionMapper;

    @Resource
    BidBackCompareMapper bidBackCompareMapper;


    @Resource
    WordUtil wordUtil;

    @Resource
    BidDocumentRecordArticleMapper bidDocumentRecordArticleMapper;

    @Resource
    OrderBaseInfoMapper orderBaseInfoMapper;

    @Resource
    TextSelfMd5Mapper textSelfMd5Mapper;


    @Resource
    MatchService matchService;



    @Resource
    TRoleMapper tRoleMapper;

    @Resource
    UserInfoMapper userInfoMapper;

    @Resource
    BackService backService;

    @Resource
    TUserRoleMapper tUserRoleMapper;

    @Resource
    UserUtil userUtil;

    @Resource
    RolePermissionService rolePermissionService;

    @Resource
    EmployeeMapper employeeMapper;

    @Resource
    HttpSession session;

    @Resource
    HttpServletRequest request;

//    @Value("${upload.temprarPath}")
//    public String temprarPath;

    // 提交后在wosbasic表添加记录
//    @Async
    public void addWosRe(BidDocumentRecordArticle bidDocumentRecordArticle) {


        //splitType: 2
        //txtComIds: 4,3,2
        Integer pushFlag = 0;
        Integer split = 1;
        Integer deptId = 1;
        String path = bidDocumentRecordArticle.getFilePath();
        String path2 = null;
        String annex = "";
        String content = "";
        String context = null;
        String selfTxt = "1";
        String txtComIds = null;
        String simi = "30";
        Integer masterId = null;
        String master = "Master_导师";
        String author = "author";
        Integer uid = bidDocumentRecordArticle.getUid();
        if (StringUtil.isNotNull(uid)) {
            UserInfo userInfo = userInfoMapper.selectById(uid);
            if (userInfo != null) {
                author = userInfo.getName();
            }
        }
        String belongDate = DateUtil.todayToyyyyMMdd();
        String title = bidDocumentRecordArticle.getFileName();
        Integer fileType = null;
        Integer splitType = 2;
        Integer bidID = bidDocumentRecordArticle.getId();

        /**
         * 如果是多个PDF上传
         */
//        Enumeration<String> parameterNames = request.getParameterNames();
//        while (parameterNames.hasMoreElements()) {
//            String s = parameterNames.nextElement();
//            String parameter = request.getParameter(s);
//            System.out.println(s);
//            System.out.println(parameter);
//            System.out.println("+++++++++++++++++++++");
//        }

        log.info("selftxt+" + selfTxt);
        if (fileType != null && fileType == 2) {
            if (path.contains("#P#D#F#")) {
                String pdfPath = localDateFilePath() + "MERGE_" + System.currentTimeMillis() + ".PDF";
                String[] paths = path.split("#P#D#F#");
                List<String> strings = Arrays.asList(paths);
                List<String> list = new ArrayList<>();
                for (String string : strings) {
                    list.add(uploadPath + string);
                }
                boolean succ = PDFMERGE.mergePdfFiles(list, uploadPath + pdfPath);
                if (succ) {
                    path = pdfPath;
                } else {
                    CheckUtil.check(false, "多文件PDF合并错误");
                }
            }
        }

        /**
         * 如果已经填写了PMID/DOI/UT 则需要给他们获取全文
         */
        String orgcontent = content;
        if (null != content) {
            boolean nextFlag = false;
            if (content.length() > 20) {
                //  10.2174/1573405618666220415122843 这样的doi 填写不了啊 超过20位了  我先注释掉了 gcr
//                return new ResultBean<>(3, "请正确填写pmid/doi/ut号,请选择一种补充");
            }
            if (content.contains("doi:") || content.startsWith("10.")) {
                try {
                    content = content.toLowerCase().replaceAll("doi:", "").trim();
                    Map<String, Object> paramMap = new HashMap<>();
                    paramMap.put("term", URLEncoder.encode(content, "utf-8"));
                    String result = HttpRequest.post("http://165.140.240.249:808/pm-newsearch.php").header(Header.USER_AGENT, "Hutool http")//头信息，多个头信息多次调用此方法即可
                            .form(paramMap)//表单内容
                            .timeout(30000)//超时，毫秒
                            .execute().body();
                    cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(result);
                    if (jsonObject.get("type").equals(1)) {
                        cn.hutool.json.JSONObject info = JSONUtil.parseObj(JSONUtil.parseArray(jsonObject.getStr("list")).get(0));
                        String pmid = info.getStr("pmid");
                        if (null != pmid) {
                            content = pmid;
                            log.info("根据 DOI 获取到的 PMID 是___" + content);
                        }
                    }
                } catch (Exception e) {

                }
            }
        }
        /**
         * 获取上传人
         */
        int loginIdAsInt = bidDocumentRecordArticle.getUid();
        Integer logid = loginIdAsInt;
        UserInfo userInfo = userInfoMapper.selectById(loginIdAsInt);
        String uname = userInfo.getName();
        Integer gid = userUtil.getGid();
        String dept = "dept";
        WosBasic wosBasic = new WosBasic();
        wosBasic.setUploadName(uname);
        wosBasic.setTxtComIds(txtComIds);
        wosBasic.setUid(loginIdAsInt);
        wosBasic.setGid(gid);
        wosBasic.setAuthor(author);
        wosBasic.setBidId(bidID);
        wosBasic.setMaster(master);
        wosBasic.setMasterId(masterId);
        wosBasic.setBelongDate(belongDate);
        wosBasic.setDeptName(dept);
        if (common.util.StringUtil.isNotNull(selfTxt)) {
            wosBasic.setSelfTxt(Integer.parseInt(selfTxt));
        }
        wosBasic.setDeptId(deptId);
        log.info("额外处理获取ut号获取处理过之前的的pmid 是+" + orgcontent);
        //进行获取我的情况查询ut号码
        if (common.util.StringUtil.isNotNull(orgcontent)) {
            if (orgcontent.contains("doi:") || orgcontent.startsWith("10.")) {
                String getut = manualCheckService.getut(orgcontent);
                String getdoiTimeYear = manualCheckService.getdoiTimeYear(orgcontent);
                log.info("通过我的方法获取ut号是" + getut);
                log.info("通过我的方法获取发表时间是" + getdoiTimeYear);
                if (common.util.StringUtil.isNotNull(getut)) {
                    wosBasic.setCUt(getut);
                }
                if (common.util.StringUtil.isNotNull(getdoiTimeYear)) {
                    wosBasic.setCPy(getdoiTimeYear);
                }
            }
        }

        try {
            if (common.util.StringUtil.isNull(wosBasic.getCPm())) {
                if (content.length() >= 7 && content.length() <= 8) {
                    log.info("存入了pm+" + content);
                    // 需要加入ut  因为有的文章在pm库也在ut 需要都排除下
                    String getpmutmatch = manualCheckService.getpmutmatch(content);
                    if (common.util.StringUtil.isNull(wosBasic.getCUt()) && common.util.StringUtil.isNotNull(getpmutmatch)) {
                        log.info("存入了pm 对应的ut+" + getpmutmatch);
                        wosBasic.setCUt(getpmutmatch);
                    }

                    wosBasic.setCPm(content);
                }
            }
            if (common.util.StringUtil.isNull(wosBasic.getCUt())) {
                if (content.length() >= 14 && content.length() <= 15) {
                    log.info("存入了ut+" + content);
                    String getpmutmatch = manualCheckService.getpmutmatch(content);
                    if (common.util.StringUtil.isNull(wosBasic.getCPm()) && common.util.StringUtil.isNotNull(getpmutmatch)) {
                        log.info("存入了ut 对应的pm+" + getpmutmatch);
                        wosBasic.setCPm(getpmutmatch);

                    }
                    wosBasic.setCUt(content);
                }
            }
            if (common.util.StringUtil.isNull(wosBasic.getCPy())) {
                Integer pmut = 2;
                if (content.length() == 14 || content.length() == 15) {
                    pmut = 1;
                }
                Integer selfArtYear = ManualCheckService.getpmutYear(content, pmut);
                if (common.util.StringUtil.isNotNull(selfArtYear)) {
                    log.info("设置了年份selfArtYear" + selfArtYear);
                    wosBasic.setCPy(selfArtYear + "");
                }
            }

        } catch (Exception e) {
        }
        wosBasic.setFileType(fileType);
        wosBasic.setFilePath(path);//
        wosBasic.setPdfUrl(getPdf(content));
        wosBasic.setCTi(title);
        wosBasic.setAnnex(annex);//附件
        wosBasic.setSplit(split);
        wosBasic.setAdmCheck(0);
        wosBasic.setSplitType(splitType);
        //如果是导师上传的,则只能管理员查看
//        if (sysUser.getPermission() == 2 || sysUser.getPermission() == 1) {
//            wosBasic.setAdmCheck(1);
//        }
        wosBasicMapper.insert(wosBasic);

        long start1 = System.currentTimeMillis();
        WosBasic wosBasic1 = wosBasicMapper.selectById(wosBasic.getId());
        // 文字拆分放在这里
        if (splitType != null && splitType == 2) {

            wosBasic1.setSoType(3);
            if (org.apache.commons.lang.StringUtils.isNotEmpty(simi)) {
                wosBasic1.setSimi(simi);
            } else {
                log.info("没有传递默认传30相似度");
                wosBasic1.setSimi("30");
            }
            if (org.apache.commons.lang.StringUtils.isNotEmpty(path2)) {
                Integer integer = manualCheckService.dealMulCheck(path, path2, author, title);
                wosBasic1.setReFiD(integer);
                wosBasic1.setSplitAs(1);
            } else {
                Integer integer = 0;
                if (org.apache.commons.lang.StringUtils.isEmpty(path)) {
                    integer = manualCheckService.dealSinCheck(0, context, author, title, path, content, logid);
                } else {
                    integer = manualCheckService.dealSinCheck(2, context, author, title, path, content, logid);
                }
                wosBasic1.setReFiD(integer);
                wosBasic1.setSplitAs(0);
            }
        } else {

            if (splitType != null && splitType == 3) {
                log.info("前台走了下图文 进行文字拆分到表里面");
                Integer integer = 0;
                if (org.apache.commons.lang.StringUtils.isEmpty(path)) {
                    integer = manualCheckService.dealSinCheck(0, context, author, title, path, content, logid);
                } else {
                    integer = manualCheckService.dealSinCheck(2, context, author, title, path, content, logid);
                }
                wosBasic1.setReFiD(integer);
                wosBasic1.setSplitAs(0);
            }
            wosBasic1.setSoType(2);
        }
        wosBasicMapper.updateById(wosBasic1);
        SmallTool.printMessLongTimeTake("拆分测试耗时+", start1);
        //发送邮件
        //sendEmail(author, FileUtil.file(uploadPath + path));
//        sysUser.setUploadCount(sysUser.getUploadCount() + 1);
        wosBasic.setUploadName(uname);
//        sysUserMapper.updateById(sysUser);

    }

    public static String getPath(String sendPath) {
        //  返回的当前路径 /home/analysis_ruijin/
        // // 此方法只适用于非tomcat 启动才可以
        String projectPath = System.getProperty("user.dir") + "/" + sendPath + "/";
        if (!cn.hutool.core.io.FileUtil.exist(projectPath)) {
            cn.hutool.core.io.FileUtil.mkdir(projectPath);
        }
        log.info("项目路径：" + projectPath);
        return projectPath;
    }

    //添加自定义上传文档到我的文献表
    public void delAddMySelfTextDb(String path) {
        TextSelfDb textSelfDb = new TextSelfDb();
        textSelfDb.setUid(userUtil.getUid());
        textSelfDb.setTableId(userUtil.getUid());
        String[] strings = path.split("/");
        String fileName = strings[strings.length - 1];
        textSelfDb.setFileName(fileName);
        textSelfDb.setPath(path);
        String pathFrom = uploadPath;
        String tempName = textSelfDb.getPath();
        String finalPath = pathFrom + tempName;
        String md5 = "";
        if (cn.hutool.core.io.FileUtil.exist(finalPath)) {
            File file = new File(finalPath);
            md5 = SecureUtil.md5(file);
        }
        textSelfDb.setInsSta(0);
        textSelfDb.setDel(0);
        checkIns(md5, textSelfDb);

    }

    /**
     * 校验自建库重复入库文件 过滤使用 给瑞金
     *
     * @param md5
     * @param textSelfDb
     */
    public void checkIns(String md5, TextSelfDb textSelfDb) {
        if (common.util.StringUtil.isNotNull(md5)) {
            List<TextSelfDb> fileMd5 = textSelfDbMapper.selectList(new QueryWrapper<TextSelfDb>().eq("file_md5", md5));
            if (fileMd5.size() > 0) {
                System.out.println("有重复过滤入库 md5+" + md5);
                common.util.CheckUtil.check(false, "重复文件+" + fileMd5.get(0).getFileName());
            } else {
                textSelfDb.setFileMd5(md5);
                textSelfDbMapper.insert(textSelfDb);
                Integer id = textSelfDb.getId();
                TextSelfDb textSelfDbParam = textSelfDbMapper.selectById(id);
                common.util.CheckUtil.check(common.util.StringUtil.isNotNull(textSelfDbParam), "非法请求");
                common.util.CheckUtil.check(textSelfDbParam.getInsSta() != 1, "已入库,重复入库");
                extraInfo(textSelfDbParam);
            }
        }
    }


    //解析我的文件到es
    @SneakyThrows
    @Async
    public void extraInfo(TextSelfDb textSelfDb) {
        textSelfDb.setFileId(textSelfDb.getId());
        String path = uploadPath;
        String tempName = textSelfDb.getPath();
        String finalPath = path + tempName;
        log.info("finalPath+" + finalPath);
        try {
            if (cn.hutool.core.io.FileUtil.exist(finalPath)) {
                String dirPath = new File(finalPath).getParentFile().getPath();
                log.info("文件路径+" + dirPath);
                List<String> strListb = new ArrayList<>();
                if (VerifyUtil.isPdf(finalPath)) {
                    if (StrUtils.isRuiJin()) {
                        strListb = pdfToTxtRuijin(dirPath, path + tempName);
                    } else {
                        strListb = PdfUtil.pdfToTxt(dirPath, path + tempName);
                    }
                } else if (VerifyUtil.isWord(finalPath)) {
                    strListb = wordUtil.wordToText(finalPath);
                }
                if (strListb != null) {
                    log.info("strListb+size+" + strListb.size());
                    log.info("pdf或者word解析出来的数量+" + strListb.size());
                    // 入库
                    List<FileDetailsTxt> pdf = new ArrayList<>();
                    //后期这个可以当做这个人全部es库
                    for (String s : strListb) {
                        if (org.apache.commons.lang3.StringUtils.isNotEmpty(s)) {
                            FileDetailsTxt fileDetails = new FileDetailsTxt();
                            fileDetails.setTxtContent(s);
                            pdf.add(fileDetails);
                        }
                    }
                    log.info("句子解析出的数量+" + pdf.size());
                    if (pdf.size() > 0) {
                        matchService.dealManualData(pdf, textSelfDb.getFileId(), textSelfDb.getTableId());
                    }
                    textSelfDb.setInsSta(1);
                    textSelfDb.setDel(0);
                } else {
                    log.info("文件解析异常");
                    textSelfDb.setInsSta(2);
                }

            } else {
                log.error("文件丢失");
                textSelfDb.setInsSta(2);
            }
        } catch (Exception e) {
            log.error("es 入库失败");
            textSelfDb.setInsSta(2);
            e.printStackTrace();
        }
        textSelfDbMapper.updateById(textSelfDb);
    }


    @SneakyThrows
    // 删除名下 全部记录
    public void delInfoUpTableRecord(TextSelfDb textSelfDb) {
        // 删除本人名下全部es 记录表
        String path = textSelfDb.getPath();
        if (common.util.StringUtil.isNotNull(path)) {
            List<TextSelfMd5> path1 = textSelfMd5Mapper.selectList(new QueryWrapper<TextSelfMd5>().eq("path", path));
            for (TextSelfMd5 textSelfMd5 : path1) {
                textSelfMd5Mapper.deleteById(textSelfMd5);
            }
        }
    }


    /**
     * 解压文件使用
     *
     * @param zipFilePath  带解压文件
     * @param outputFolder 解压到的目录
     */
    public static List<File> unzipFile(String zipFilePath, String outputFolder) {
        List<File> resFiles = new ArrayList<>();

        // 替换成了apache的 原有默认的会报错 Java原生库解压Zip流报MALFORMED错
        try (FileInputStream fis = new FileInputStream(zipFilePath);
             ZipArchiveInputStream zis = new ZipArchiveInputStream(new BufferedInputStream(fis))) {
            ZipArchiveEntry entry;
            while ((entry = zis.getNextZipEntry()) != null) {
                File entryDestination = new File(outputFolder, entry.getName());
                if (entry.isDirectory()) {
                    entryDestination.mkdirs();
                } else {
                    createParentDirs(entryDestination);
                    try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(entryDestination))) {
                        byte[] buffer = new byte[1024];
                        int read;
                        while ((read = zis.read(buffer)) != -1) {
                            bos.write(buffer, 0, read);
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<File> files = cn.hutool.core.io.FileUtil.loopFiles(outputFolder);
        if (files.size() > 0) {
            resFiles = files;
        }
        return resFiles;

    }

    private static void createParentDirs(File file) throws IOException {
        File parentDir = file.getParentFile();
        if (parentDir != null && !parentDir.exists() && !parentDir.mkdirs()) {
            throw new IOException("Could not create parent directories for " + file);
        }
    }

    /**
     * 解压RAR压缩文件到指定路径
     *
     * @param rarPath RAR压缩文件
     * @param dstDir  解压到的文件夹路径
     */
    public static List<File> unRarFile(String rarPath, String dstDir) throws Exception {

        List<File> resFiles = new ArrayList<>();
        File dstDiretory = new File(dstDir);
        if (!dstDiretory.exists()) {
            dstDiretory.mkdirs();
        }
        try {
            File rarFile = new File(rarPath);
            Archive archive = new Archive(new FileInputStream(rarFile));
            List<FileHeader> fileHeaders = archive.getFileHeaders();
            for (FileHeader fileHeader : fileHeaders) {
                if (fileHeader.isDirectory()) {
                    String fileName = fileHeader.getFileNameW();
                    if (!existZH(fileName)) {
                        fileName = fileHeader.getFileNameString();
                    }
                    File dir = new File(dstDir + File.separator + fileName);
                    if (!dir.exists()) {
                        dir.mkdirs();
                    }
                } else {
                    String fileName = fileHeader.getFileNameW().trim();
                    if (!existZH(fileName)) {
                        fileName = fileHeader.getFileNameString().trim();
                    }
                    File file = new File(dstDir + File.separator + fileName);
                    try {
                        if (!file.exists()) {
                            if (!file.getParentFile().exists()) {
                                file.getParentFile().mkdirs();
                            }
                            file.createNewFile();
                        }
                        FileOutputStream os = new FileOutputStream(file);
                        archive.extractFile(fileHeader, os);
                        os.close();
                    } catch (Exception ex) {
                        throw ex;
                    }
                }
            }
            archive.close();
            List<File> files = cn.hutool.core.io.FileUtil.loopFiles(dstDir);
            if (files.size() > 0) {
                resFiles = files;
            }

        } catch (Exception e) {
            throw e;
        }
        return resFiles;
    }

    public static boolean existZH(String str) {
        String regEx = "[\\u4e00-\\u9fa5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        while (m.find()) {
            return true;
        }
        return false;
    }

    //根据用户id获取全部菜单
    public HomeRespVO getHomeInfo(Integer userId) {
        Employee sysUser = employeeMapper.selectById(userId);
        HomeRespVO respVO = new HomeRespVO();
        // 抹掉一些关键信息
        sysUser.setPassword("");
        sysUser.setOpenPassword("");
        if (sysUser != null) {
//            List<PermissionRespNode> menus = this.permissionTreeList(userId);
            Integer roleid = (Integer) session.getAttribute("roleid");
            List<PermissionRespNode> menus = this.permissionTreeListByRoleid(roleid);
            respVO.setUserInfo(sysUser);
            respVO.setMenus(menus);
        }
        return respVO;
    }

    public void addUserInfo(List<BidDocumentRecordArticle> ls) {
        List<UserInfo> userInfos = userInfoMapper.selectList(null);
        Map<Integer, String> collect = userInfos.stream().collect(Collectors.toMap(UserInfo::getId, UserInfo::getName));
        for (BidDocumentRecordArticle l : ls) {
            if (collect.containsKey(l.getUid())) {
                l.setUidStr(collect.get(l.getUid()));
            }

        }
    }

    //解析我的文件到es
    @SneakyThrows
    @Async
//    public void extraInfo(TextSelfDb textSelfDb) {
//        textSelfDb.setFileId(textSelfDb.getId());
//        String path = uploadPath;
//        String tempName = textSelfDb.getPath();
//        String finalPath = path + tempName;
//        log.info("finalPath+" + finalPath);
//        try {
//            if (cn.hutool.core.io.FileUtil.exist(finalPath)) {
//                String dirPath = new File(finalPath).getParentFile().getPath();
//                log.info("文件路径+" + dirPath);
//                List<String> strListb = new ArrayList<>();
//                if (VerifyUtil.isPdf(finalPath)) {
//                    if (StrUtils.isRuiJin()) {
//                        strListb = pdfToTxtRuijin(dirPath, path + tempName);
//                    } else {
//                        strListb = PdfUtil.pdfToTxt(dirPath, path + tempName);
//                    }
//                } else if (VerifyUtil.isWord(finalPath)) {
//                    strListb = wordUtil.wordToText(finalPath);
//                }
//                if (strListb != null) {
//                    log.info("strListb+size+" + strListb.size());
//                    log.info("pdf或者word解析出来的数量+" + strListb.size());
//                    // 入库
//                    List<FileDetailsTxt> pdf = new ArrayList<>();
//                    //后期这个可以当做这个人全部es库
//                    for (String s : strListb) {
//                        if (org.apache.commons.lang3.StringUtils.isNotEmpty(s)) {
//                            FileDetailsTxt fileDetails = new FileDetailsTxt();
//                            fileDetails.setTxtContent(s);
//                            pdf.add(fileDetails);
//                        }
//                    }
//                    log.info("句子解析出的数量+" + pdf.size());
//                    if (pdf.size() > 0) {
//                        matchService.dealManualData(pdf, textSelfDb.getFileId(), textSelfDb.getTableId());
//                    }
//                    textSelfDb.setInsSta(1);
//                    textSelfDb.setDel(0);
//                } else {
//                    log.info("文件解析异常");
//                    textSelfDb.setInsSta(2);
//                }
//
//            } else {
//                log.error("文件丢失");
//                textSelfDb.setInsSta(2);
//            }
//        } catch (Exception e) {
//            log.error("es 入库失败");
//            textSelfDb.setInsSta(2);
//            e.printStackTrace();
//        }
//        textSelfDbMapper.updateById(textSelfDb);
//    }


    public void delInfo(TextSelfDb textSelfDb) {
        // 删除本人名下全部es 入库数据 2024年4月28日08:38:00
        try {
            String index = IndexConfig.SELF_TETX_INDEX;
            BoolQuery.Builder allQueryBuilder = new BoolQuery.Builder();
            TermQuery fileId = TermQuery.of(i -> i.field("file_id").value(textSelfDb.getFileId()));
            TermQuery tableId = TermQuery.of(i -> i.field("table_id").value(textSelfDb.getTableId()));
            allQueryBuilder.must(fileId._toQuery());
            allQueryBuilder.must(tableId._toQuery());
            Query query = allQueryBuilder.build()._toQuery();
            DeleteByQueryRequest deleteByQueryRequest = DeleteByQueryRequest.of(s -> s.index(index).query(query));
            DeleteByQueryResponse deleteByQueryResponse = client.deleteByQuery(deleteByQueryRequest);
            System.out.println("Deleted " + deleteByQueryResponse.total() + " documents.");
            textSelfDb.setDel(1);
            textSelfDb.setInsSta(0);
            textSelfDbMapper.updateById(textSelfDb);
        } catch (Exception e) {
            textSelfDb.setDel(1);
            textSelfDb.setInsSta(0);
            textSelfDbMapper.updateById(textSelfDb);
            e.printStackTrace();

        }


    }

    //    MultipartFile file = request.getFile("file");
    //        //年份
    //        String year = request.getParameter("year");
    //        // 级别
    //        String level = request.getParameter("level");
    //        //机构
    //        String ins = request.getParameter("ins");
    public void addManyFilesToRecord(MultipartFile file, String year, String level, String ins) {
        boolean b = FileUtil.checkFileRAR(file);
        if (b) {
            log.info("走了压缩文件测试");
            List<File> files = checkFileUnzip(file);
            log.info("压缩文件解压后的文件数量是" + files.size());
            BackImEntity backImEntity = new BackImEntity();
            backImEntity.setYear(year);
            backImEntity.setLevel(level);
            backImEntity.setIns(ins);
            for (File path : files) {
                try {
                    //解析入库
                    BiaoshuEntity biaoshuEntity = backService.parsePdfToEntity(null, path, backImEntity);
                    //提取内容更新进去
                    BidBackCompare bidBackCompare = bidBackCompareMapper.selectOne(new QueryWrapper<BidBackCompare>().eq("bid", biaoshuEntity.getBdraid()));
                    bidBackCompare.setModi(JSONObject.toJSONString(biaoshuEntity));
                    bidBackCompareMapper.updateById(bidBackCompare);
                    //更新状态入库
                    BidDocumentRecordArticle bidDocumentRecordArticle = bidDocumentRecordArticleMapper.selectById(biaoshuEntity.getBdraid());
                    CheckUtil.check(StringUtil.isNotNull(bidDocumentRecordArticle), "非法访问 不能空");
                    bidDocumentRecordArticle.setStat(3);
                    bidDocumentRecordArticle.setUpti(LocalDateTime.now());
                    bidDocumentRecordArticleMapper.updateById(bidDocumentRecordArticle);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            // 不是压缩包 是默认文件
            log.info("不是压缩吧是默认的文件");
            try {
                //解析入库
                BiaoshuEntity biaoshuEntity = backService.parsePdfToEntity(file, null, null);

                //提取内容更新进去
                BidBackCompare bidBackCompare = bidBackCompareMapper.selectOne(new QueryWrapper<BidBackCompare>().eq("bid", biaoshuEntity.getBdraid()));
                bidBackCompare.setModi(JSONObject.toJSONString(biaoshuEntity));
                bidBackCompareMapper.updateById(bidBackCompare);
                //更新状态入库
                BidDocumentRecordArticle bidDocumentRecordArticle = bidDocumentRecordArticleMapper.selectById(biaoshuEntity.getBdraid());
                CheckUtil.check(StringUtil.isNotNull(bidDocumentRecordArticle), "非法访问 不能空");
                bidDocumentRecordArticle.setStat(3);
                bidDocumentRecordArticle.setUpti(LocalDateTime.now());
                bidDocumentRecordArticleMapper.updateById(bidDocumentRecordArticle);
            } catch (Exception e) {
                e.printStackTrace();
            }


        }

    }

    public void dealSpNsfc(Nsfc nsfc) {
        String var9 = nsfc.getVar9();
        String var20 = nsfc.getVar20();
        String var26 = nsfc.getVar26() == null ? "" : nsfc.getVar26();
        if (StringUtil.isNotNull(var9)) {
            nsfc.setVar9(var9.replace("；", ";"));
        }
        if (StringUtil.isNotNull(var20)) {
            nsfc.setVar20(var20.replace("；", ";"));
        }

//        Map<String, String> top = new HashMap<>();
//        top.put("A", "数理科学部");
//        top.put("B", "化学科学部");
//        top.put("C", "生命科学部");
//        top.put("D", "地球科学部");
//        top.put("E", "工程与材料科学部");
//        top.put("F", "信息科学部");
//        top.put("G", "管理科学部");
//        top.put("H", "医学科学部");
        //添加其他数据
        //

        if (StringUtil.isNotNull(var26)) {
            String[] split = var26.split("-");
            if (split.length >= 2) {
                nsfc.setSubject(split[split.length - 1]);
                nsfc.setTopsubject(split[0]);
            } else {
                nsfc.setSubject("");
                nsfc.setTopsubject(split[0]);
            }
        }

//        try {
//            nsfc.setSubject(var26);
//        } catch (Exception e) {
//        }
//        try {
////            nsfc.setTopsubject((top.get(nsfc.getVar15().substring(0, 1))));
//            nsfc.setTopsubject("");
//        } catch (Exception e) {
//        }





    }

    @SneakyThrows
    public List<File> checkFileUnzip(MultipartFile file) {
        List<File> res = new ArrayList<>();
        String originalFilename = file.getOriginalFilename();
        if (originalFilename.toLowerCase().contains(".rar") || originalFilename.toLowerCase().contains(".zip")) {
            String saveFileName = System.currentTimeMillis() + "___" + originalFilename;
            Calendar calendar = Calendar.getInstance();
            String date = "" + calendar.get(Calendar.YEAR) + (calendar.get(Calendar.MONTH) + 1) + calendar.get(Calendar.DATE);
            String finalFilePath = getPath(date) + saveFileName;
            String unrarPath = getPath(date) + System.currentTimeMillis() + "/unpath/";
            file.transferTo(new File(finalFilePath));
            if (cn.hutool.core.io.FileUtil.exist(finalFilePath)) {
                // 根据数据进行解压判断
                if (originalFilename.contains(".zip")) {
                    System.setProperty("sun.zip.encoding", System.getProperty("sun.jnu.encoding"));
                    // 这就是全部解压的后的文件集合
                    res = unzipFile(finalFilePath, unrarPath);
                } else {
                    res = unRarFile(finalFilePath, unrarPath);
                }
            }
        }
        return res;
    }

    public Map<String, Integer> themerank(String s, String end, Integer type) {

        Map<String, Integer> resRank = new LinkedHashMap<>();
        LocalDateTime localDateTime = DateUtil.StringToDateLocalDateTime(s);
        LocalDateTime endd = DateUtil.StringToDateLocalDateTime(end);
        QueryWrapper<OrderBaseInfo> queryWrapper = new QueryWrapper();
        queryWrapper.ge("addtime", localDateTime);
        queryWrapper.le("addtime", endd);
        List<OrderBaseInfo> orderBaseInfos = orderBaseInfoMapper.selectList(queryWrapper);
        for (OrderBaseInfo orderBaseInfo : orderBaseInfos) {
            String searchWordEn = "";
            //类型 1 主题 2 单位文献数 3 单位查新数量
            String[] split = new String[]{};
            if (type == 1) {
                if (StringUtil.isNotNull(orderBaseInfo.getSearchWordEn())) {
                    searchWordEn = orderBaseInfo.getSearchWordEn();
                }
                if (StringUtil.isNotNull(orderBaseInfo.getSearchWordCn())) {
                    searchWordEn = searchWordEn + ";" + orderBaseInfo.getSearchWordCn();
                }
                split = searchWordEn.split(";");
            } else if (type == 3) {
                if (StringUtil.isNotNull(orderBaseInfo.getUnitName())) {
                    searchWordEn = orderBaseInfo.getUnitName();
                }

                split = searchWordEn.split(";");
            }

            for (String string : split) {
                String key = string.toLowerCase().trim();
                resRank.compute(key, (k, v) -> {
                    if (v == null) {
                        v = 0;
                    }
                    v++;
                    return v;
                });
            }
            Map<String, Integer> stringIntegerMap = StringUtil.strMapSortValueInt(resRank, 10);
            return stringIntegerMap;
        }
        return resRank;
    }

    public void checksearchStrategy(OrderBaseInfo orderBaseInfo) {
        // 校验必须是; 进行分割的检索词组

        boolean b = backService.checkIsyS(orderBaseInfo);
        if (b) {
            log.info("checkIsyS 不校验检索式");
//            String searchWordEn = orderBaseInfo.getSearchWordEn();
//            String searchWordCn = orderBaseInfo.getSearchWordCn();
//            if (StringUtil.isNotNull(searchWordEn)) {
//                CheckUtil.check(searchWordEn.contains(";"), "检索词必须用;进行分割");
//            }
//            if (StringUtil.isNotNull(searchWordCn)) {
//                CheckUtil.check(searchWordCn.contains(";"), "检索词必须用;进行分割");
//            }
//            searchWordEn = searchWordEn.replace("；", ";");
//            searchWordCn = searchWordCn.replace("；", ";");
//            orderBaseInfo.setSearchWordCn(searchWordCn);
//            orderBaseInfo.setSearchWordEn(searchWordEn);
        } else {
            String searchWordEn = orderBaseInfo.getSearchWordEn();
            String searchWordCn = orderBaseInfo.getSearchWordCn();
            if (StringUtil.isNotNull(searchWordEn)) {
                CheckUtil.check(searchWordEn.contains(";"), "检索词必须用;进行分割");
            }
            if (StringUtil.isNotNull(searchWordCn)) {
                CheckUtil.check(searchWordCn.contains(";"), "检索词必须用;进行分割");
            }
            searchWordEn = searchWordEn.replace("；", ";");
            searchWordCn = searchWordCn.replace("；", ";");
            orderBaseInfo.setSearchWordCn(searchWordCn);
            orderBaseInfo.setSearchWordEn(searchWordEn);
        }

    }

    // 校验当前用户有没有管理员权限
    public boolean checkUserAdminRole() {
        boolean res = false;
        try {
            List<Integer> roleIds = (List<Integer>) session.getAttribute("roleall");
            if (roleIds.contains(Constants.单位管理员)) {
                res = true;
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        // 校验必须是; 进行分割的检索词组

        return res;


    }

    //根据角色获取全部的按钮
    public List<TPermission> getPermissionIconByRoleId(Integer roleId) {
        log.info("根据roleid 获取菜单roleId++" + roleId);
        List<Integer> roleIds = Stream.of(roleId).collect(Collectors.toList());
        if (roleIds.size() > 0) {
            List<Integer> perByRoleId = rolePermissionService.getPerByRoleId(roleIds);
            List<TPermission> tPermissions = tPermissionMapper.selectBatchIds(perByRoleId).stream().filter(o -> o.getType() == 3).collect(Collectors.toList());
            return handleNoPermission(tPermissions);
        } else {
            return null;
        }
    }


//    public static void main(String[] args) {
//        String as = "1950—2020年10月";
//        boolean b = checkSearchToolsYearRange(as);
//        System.out.println(b);
//    }

    public boolean checkSearchToolsYearRange(SearchTools searchTools) {
        String year = searchTools.getYearRange();
        year = year.replace("—", "-");
        searchTools.setYearRange(year);
        boolean isTrue = true;
        if (StringUtil.isNull(year)) {
            return false;
        }
        String sp = "—";
        String sp2 = "-";
        boolean isCon = false;
        if (year.contains(sp2)) {
            sp = sp2;
            isCon = true;
        } else if (year.contains(sp)) {
            isCon = true;
        }

        if (isCon && year.contains(sp)) {
            String[] split = year.split("-");
            if (split.length != 2) {
                return false;
            } else {
                String startYeatr = split[0];
                String startYeatrEnd = split[1];
                if (startYeatr.length() != 4) {
                    return false;
                } else {
                    if (!startYeatrEnd.contains("年") || !startYeatrEnd.contains("月")) {
                        return false;
                    }

                }
            }
        } else {
            return false;
        }


        return isTrue;
    }


    //设置了动态刷新当前项目的数据展示
    public void addSearchArtSizeToOrderBaseInfo(OrderBaseInfo orderBaseInfo, List<SearchTools> searchTools) {
        List<SearchTools> collect = searchTools.stream().filter(o -> o.getStat() == 0).collect(Collectors.toList());
        log.info("计算前工具数量+" + collect);
        int searchAll = 0;
        int searchReal = 0;
        int SIMIsearchReal = 0;
        long lstart = System.currentTimeMillis();
        long lend = System.currentTimeMillis();
        for (SearchTools tools : collect) {
            if (StringUtil.isNotNull(tools.getYearRange())) {
                String yearRange = tools.getYearRange();
                String[] split = yearRange.split("-");
                if (split.length == 1) {
                    split = yearRange.split("—");
                }
                long start1 = DateUtil.yyyyToLong(split[0]);
                long end1 = DateUtil.yyyy年MM月ToLong(split[1]);
                if (start1 <= lstart) {
                    lstart = start1;
                }
                if (end1 <= lend) {
                    lend = end1;
                }

            }
            try {
                String searchSize = tools.getSearchSize();
                searchAll += Integer.parseInt(searchSize.replace("+", ""));
            } catch (Exception e) {
                e.printStackTrace();

            }
            try {
                String searchReal1 = tools.getSearchReal();
                searchReal += Integer.parseInt(searchReal1.replace("+", ""));
            } catch (Exception e) {
                e.printStackTrace();

            }
            try {
                String simi = tools.getSimi();
                SIMIsearchReal += Integer.parseInt(simi.replace("+", ""));
            } catch (Exception e) {
                e.printStackTrace();

            }
        }
        String yearRange = DateUtil.longToDate_y(lstart) + "-" + DateUtil.longToDate_ym(lend);
        log.info("更新后数量检索文献总量+" + searchAll);
        log.info("检出文献量+" + searchReal);
        log.info("密切相关文献量+" + SIMIsearchReal);
        log.info("工具数量+" + collect.size());
        log.info("年限格式+" + yearRange);
        //     /**
        //     * 检索文献总量
        //     */
        //    private String backAllsize;
        //
        //    /**
        //     * 检出文献量
        //     */
        //    private String backMatch;
        //
        //    /**
        //     * 密切相关文献量
        //     */
        //    private String backMiqie;
        if (orderBaseInfo != null) {
            orderBaseInfo.setBackAllsize(searchAll + "+");
            orderBaseInfo.setBackMatch(searchReal + "");
            orderBaseInfo.setBackMiqie(SIMIsearchReal + "");
            orderBaseInfo.setBackTools(collect.size() + "");
            orderBaseInfo.setBackYear(yearRange);
            orderBaseInfoMapper.updateById(orderBaseInfo);
        }
    }

    public void addSearchArtSizeToOrderBaseInfoCs(OrderBaseInfo orderBaseInfo, List<SearchToolsCs> searchTools) {
        List<SearchToolsCs> collect = searchTools.stream().filter(o -> o.getStat() == 0).collect(Collectors.toList());
        log.info("计算前工具数量+" + collect);
        int searchAll = 0;
        int searchReal = 0;
        int SIMIsearchReal = 0;
        if (orderBaseInfo != null) {
            orderBaseInfo.setBackAllsize(searchAll + "+");
            orderBaseInfo.setBackMatch(searchReal + "");
            orderBaseInfo.setBackMiqie(SIMIsearchReal + "");
            orderBaseInfo.setBackTools(collect.size() + "");
            orderBaseInfoMapper.updateById(orderBaseInfo);
        }
    }

    /**
     * 根据uid获取用户拥有的角色ids
     */
    public List<Integer> getRoleIdsByUid(Integer userId) {
        List<Integer> roleIds = tUserRoleMapper.selectList(new QueryWrapper<TUserRole>().eq("user_id", userId)).stream().map(o -> o.getRoleId()).collect(Collectors.toList());
        return roleIds;
    }

    /**
     * 根据uid获取用户拥有的角色名称
     */
    public List<String> getRoleNamesByUid(Integer userId) {
        List<Integer> roleIds = tUserRoleMapper.selectList(new QueryWrapper<TUserRole>().eq("user_id", userId)).stream().map(o -> o.getRoleId()).collect(Collectors.toList());
        List<TRole> tRoles = tRoleMapper.selectBatchIds(roleIds);
        List<String> stringStream = tRoles.stream().map(o -> o.getName()).collect(Collectors.toList());
        return stringStream;
    }

    //根据前台用户提交的roleid 获取指定菜单
    public List<PermissionRespNode> permissionTreeListByRoleid(Integer roleid) {
        List<TPermission> list = getPermissionByRoleId(roleid);
        return getTree(list.stream().sorted(Comparator.comparing(TPermission::getOrderNum)).collect(Collectors.toList()), true);
    }

    public TPermission addPermission(TPermission permission) {
        verifyForm(permission);
        if (StringUtils.isEmpty(permission.getGenTime())) {
            permission.setGenTime(LocalDateTime.now());
        }
        tPermissionMapper.insert(permission);
        return permission;
    }

    /**
     * 根据用户查询拥有的权限
     * 先查出用户拥有的角色
     * 再去差用户拥有的权限
     * 也可以多表关联查询
     */
    public List<TPermission> getPermissionByRoleId(Integer roleId) {
        log.info("根据roleid 获取菜单");
        List<Integer> roleIds = Stream.of(roleId).collect(Collectors.toList());
        if (roleIds.size() > 0) {
            List<TPermission> tPermissions = tPermissionMapper.selectBatchIds((rolePermissionService.getPerByRoleId(roleIds)));
            return handleNoPermission(tPermissions);
        } else {
            return null;
        }
    }

    //2021年3月16日11:02:34  需要判断 如果根目录是0的 那么子菜单也不显示
    //type类型 1是目录 2是菜单 3 是按钮
    public List<TPermission> handleNoPermission(List<TPermission> ls) {
        //获取没有权限的id集合 进行删除
        Set<Integer> pids = new LinkedHashSet<>();
        for (TPermission l : ls) {
            if (l.getType() == 1 && l.getStatus() == 0) {
                pids.add(l.getId());
                List<Integer> collect = ls.stream().filter(o -> o.getPid().equals(l.getId())).map(o -> o.getId()).collect(Collectors.toList());
                pids.addAll(collect);
            } else if (l.getType() == 2 && l.getStatus() == 0) {
                pids.add(l.getId());
            }
        }
        List<TPermission> list = ls.stream().filter(o -> !pids.contains(o.getId())).collect(Collectors.toList());
        return list;
    }


    /**
     * 操作后的菜单类型是目录的时候 父级必须为目录
     * 操作后的菜单类型是菜单的时候，父类必须为目录类型
     * 操作后的菜单类型是按钮的时候 父类必须为菜单类型
     */
    private void verifyForm(TPermission permission) {

        TPermission parent = tPermissionMapper.selectById(permission.getPid());
        switch (permission.getType()) {
            case 1:
                if (parent != null) {
                    if (parent.getType() != 1) {
                        CheckUtil.check(false, BaseResponseCode.OPERATION_MENU_PERMISSION_CATALOG_ERROR.getMsg());
                    }
                } else if (permission.getPid() != 0) {
                    CheckUtil.check(false, BaseResponseCode.OPERATION_MENU_PERMISSION_CATALOG_ERROR.getMsg());
                }
                break;
            case 2:
                if (parent == null || parent.getType() != 1) {
                    CheckUtil.check(false, BaseResponseCode.OPERATION_MENU_PERMISSION_MENU_ERROR.getMsg());
                }
                break;
            case 3:
                if (parent == null || parent.getType() != 2) {
                    CheckUtil.check(false, BaseResponseCode.OPERATION_MENU_PERMISSION_BTN_ERROR.getMsg());
                }
                break;
            default:
                break;
        }
        /**
         * id 不为空说明是编辑
         */
//        if (!StringUtils.isEmpty(Permission.getId())) {
//            QueryWrapper queryWrapper = new QueryWrapper();
//            queryWrapper.eq("pid", Permission.getId());
//            List<Permission> list = PermissionMapper.selectList(queryWrapper);
//            if (!list.isEmpty()) {
//                throw new BusinessException(BaseResponseCode.OPERATION_MENU_PERMISSION_UPDATE);
//            }
//        }

    }

    /**
     * 删除菜单权限
     * 判断是否 有角色关联
     * 判断是否有子集
     */
    @Transactional
    public void deletedPermisson(Integer permissionId) {
        TPermission permission = tPermissionMapper.selectById(permissionId);
        if (null == permission) {
            log.error("传入 的 id:{}不合法", permissionId);
            CheckUtil.check(false, BaseResponseCode.DATA_ERROR.getMsg());
        }
        List<TPermission> childs = tPermissionMapper.selectList(new LambdaQueryWrapper<TPermission>().eq(TPermission::getPid, permissionId));
        if (!childs.isEmpty()) {
            CheckUtil.check(false, BaseResponseCode.ROLE_PERMISSION_RELATION.getMsg());
        }
        int delete = tPermissionMapper.delete(new LambdaQueryWrapper<TPermission>().eq(TPermission::getId, permissionId));
        if (delete != 1) {
            CheckUtil.check(false, BaseResponseCode.OPERATION_ERRO.getMsg());
        }
//        //删除和角色关联
//        rolePermissionService.removeByPermissionId(permissionId);
//        //刷新权限
//        httpSessionService.refreshPermission(permissionId);
    }

    /**
     * 更新菜单权限
     */
    public void updatePermission(TPermission update) {
        TPermission Permission = tPermissionMapper.selectById(update.getId());
        if (null == Permission) {
            log.error("传入 的 id:{}不合法", update.getId());
            CheckUtil.check(false, BaseResponseCode.DATA_ERROR.getMsg());
        }
        /**
         * 只有类型变更
         * 或者所属菜单变更
         */
        if (Permission.getType().equals(update.getType()) || !Permission.getPid().equals(update.getPid())) {
            verifyForm(update);
        }
        int i = tPermissionMapper.updateById(update);
        if (i != 1) {
            CheckUtil.check(false, BaseResponseCode.OPERATION_ERRO.getMsg());
        }
        /**
         * 所有管理这个菜单权限用户将重新刷新token
         */
//        if (!Permission.getPerms().equals(update.getPerms())) {
//            //刷新权限
//            httpSessionService.refreshPermission(update.getId());
//        }

    }

    /**
     * 获取所有的目录菜单树排除按钮
     * 因为不管是新增或者修改
     * 选择所属菜单目录的时候
     * 都不可能选择到按钮
     * 而且编辑的时候 所属目录不能
     * 选择自己和它的子类
     */
    public List<PermissionRespNode> selectAllMenuByTree(Integer permissionId) {
        List<TPermission> list = selectAll();
        if (!list.isEmpty() && !StringUtils.isEmpty(permissionId)) {
            for (TPermission permission : list) {
                if (permission.getId().equals(permissionId)) {
                    list.remove(permission);
                    break;
                }
            }
        }
        List<PermissionRespNode> result = new ArrayList<>();
        //新增顶级目录是为了方便添加一级目录
        PermissionRespNode respNode = new PermissionRespNode();
        respNode.setId(0);
        respNode.setTitle("默认顶级菜单");
        respNode.setSpread(true);
        respNode.setChildren(getTree(list, true));
        result.add(respNode);
        return result;
    }

    /**
     * 递归获取菜单树
     */
    private List<PermissionRespNode> getTree(List<TPermission> all, boolean type) {
        List<PermissionRespNode> list = new ArrayList<>();
        if (all == null || all.isEmpty()) {
            return list;
        }
        for (TPermission permission : all) {
            if (permission.getPid() == 0) {
                PermissionRespNode permissionRespNode = new PermissionRespNode();
                BeanUtils.copyProperties(permission, permissionRespNode);
                permissionRespNode.setTitle(permission.getName());
                if (type) {
                    permissionRespNode.setChildren(getChildExcBtn(permission.getId(), all));
                } else {
                    permissionRespNode.setChildren(getChildAll(permission.getId(), all));
                }
                list.add(permissionRespNode);
            }
        }
        return list;
    }

    /**
     * 只递归获取目录和菜单
     */
    private List<PermissionRespNode> getChildExcBtn(Integer id, List<TPermission> all) {
        List<PermissionRespNode> list = new ArrayList<>();
        for (TPermission permission : all) {
            if (permission.getPid().equals(id) && permission.getType() != 3) {
                PermissionRespNode permissionRespNode = new PermissionRespNode();
                BeanUtils.copyProperties(permission, permissionRespNode);
                permissionRespNode.setTitle(permission.getName());
                permissionRespNode.setChildren(getChildExcBtn(permission.getId(), all));
                list.add(permissionRespNode);
            }
        }
        return list;
    }

    /**
     * 递归遍历所有
     */
    private List<PermissionRespNode> getChildAll(Integer id, List<TPermission> all) {
        List<PermissionRespNode> list = new ArrayList<>();
        for (TPermission permission : all) {
            if (permission.getPid().equals(id)) {
                PermissionRespNode permissionRespNode = new PermissionRespNode();
                BeanUtils.copyProperties(permission, permissionRespNode);
                permissionRespNode.setTitle(permission.getName());
                permissionRespNode.setChildren(getChildAll(permission.getId(), all));
                list.add(permissionRespNode);
            }
        }
        return list;
    }


    public List<TPermission> selectAll() {
        List<TPermission> tPermissions = tPermissionMapper.selectList(new QueryWrapper<>());
        if (!tPermissions.isEmpty()) {
            for (TPermission Permission : tPermissions) {
                TPermission parent = tPermissionMapper.selectById(Permission.getPid());
                if (parent != null) {
                    Permission.setPpidName(parent.getName());
                }
            }
        }
        return tPermissions;
    }

    /**
     * 获取所有菜单权限按钮
     */

    public List<PermissionRespNode> selectAllByTree() {

        List<TPermission> list = tPermissionMapper.selectList(new QueryWrapper<>());
        return getTree(list, false);
    }

    /**
     * 根据用户id 获取用户角色名称
     */
    public String getRoleNameByUid(Integer uid) {
        StringBuffer stringBuffer = new StringBuffer();
        List<Integer> roleids = tUserRoleMapper.selectList(new LambdaQueryWrapper<TUserRole>().eq(TUserRole::getUserId, uid)).stream().map(o -> o.getRoleId()).collect(Collectors.toList());
        List<TRole> tRoles = tRoleMapper.selectBatchIds(roleids);
        for (TRole tRole : tRoles) {
            stringBuffer.append(tRole.getName() + ",");
        }
        String s = stringBuffer.toString();
        String substring = s.substring(0, s.length() - 1);
        return substring;
    }

    /**
     * 根据角色id 获取用户列表
     */
    public List<Employee> getEmployeeLsByRoleId(List<Integer> roleId) {
        List<Integer> uids = tUserRoleMapper.selectList(new LambdaQueryWrapper<TUserRole>().in(TUserRole::getRoleId, roleId)).stream().map(o -> o.getUserId()).collect(Collectors.toList());
        List<Employee> EmployeeS = employeeMapper.selectBatchIds(uids);
        return EmployeeS;
    }


    @SneakyThrows
    public void commonDown(String filePath) {
        String[] strings = filePath.split("/");
        String fileName = strings[strings.length - 1];
        String path = request.getServletContext().getRealPath(filePath);
        System.out.println(path);
        //设置文件路径
        File file = new File(path);
        if (file.exists()) {
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            //处理中问乱码
            String userAgent = request.getHeader("User-Agent");
            System.out.println("浏览器的头信息" + userAgent);
            /*
             * 下面这块编码有问题，不同的浏览器会出错直接统一编码
             * 2019年8月20日13:13:40
             * */
            if ((userAgent.contains("MSIE")) || (userAgent.contains("Trident"))) {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @SneakyThrows
    public void commonDownReal(String filePath) {
        String[] strings = filePath.split("/");
        String fileName = strings[strings.length - 1];
        String path = filePath;
        System.out.println(path);
        //设置文件路径
        File file = new File(path);
        if (file.exists()) {
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            //处理中问乱码
            String userAgent = request.getHeader("User-Agent");
            System.out.println("浏览器的头信息" + userAgent);
            /*
             * 下面这块编码有问题，不同的浏览器会出错直接统一编码
             * 2019年8月20日13:13:40
             * */
            if ((userAgent.contains("MSIE")) || (userAgent.contains("Trident"))) {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            }
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public void reportCommonDown(OrderBaseInfo orderBaseInfo, Integer type) throws UnsupportedEncodingException {
        String filePath = "";
        if (type == 1) {
            filePath = orderBaseInfo.getResultReportWord();
        } else if (type == 3) {
            filePath = orderBaseInfo.getChaxinContractBack();
        } else if (type == 4) {
            filePath = orderBaseInfo.getResultReportWordBack();
        } else {
            filePath = orderBaseInfo.getChaxinContract();
        }
        String[] strings = filePath.split("/");
        String fileName = strings[strings.length - 1];
        String[] names = fileName.split("\\.");
        String finalName = orderBaseInfo.getProjectNo() + "." + names[names.length - 1];
        if (type == 3 || type == 2) {
            finalName = orderBaseInfo.getProjectNo() + "合同" + "." + names[names.length - 1];
        }
        String path = request.getServletContext().getRealPath(filePath);
        //设置文件路径
        File file = new File(path);
        if (file.exists()) {
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            //处理中问乱码
            String userAgent = request.getHeader("User-Agent");
            System.out.println("浏览器的头信息" + userAgent);
            /*
             * 下面这块编码有问题，不同的浏览器会出错直接统一编码
             * 2019年8月20日13:13:40
             * */
            if ((userAgent.contains("MSIE")) || (userAgent.contains("Trident"))) {
                finalName = new String(finalName.getBytes("UTF-8"), "ISO-8859-1");
            } else {
                finalName = URLEncoder.encode(finalName, "UTF-8");
            }
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment;fileName=" + finalName);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
